{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "continuing-northern",
   "metadata": {},
   "source": [
    "## K-nearest neighbour\n",
    " \n",
    "$X_{n \\times d}$\n",
    "\n",
    "$Y_{n \\times 1}$\n",
    "\n",
    "$Z_{m \\times d}$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "recognized-seating",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import time\n",
    "from collections import Counter"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "pretty-capability",
   "metadata": {},
   "outputs": [],
   "source": [
    "n, d, m=500, 20, 4\n",
    "k=5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "differential-platinum",
   "metadata": {},
   "outputs": [],
   "source": [
    "X=np.random.random((n,d))\n",
    "Z=np.random.random((m,d))\n",
    "Y=np.random.randint(3,size=n)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "alpha-lincoln",
   "metadata": {},
   "source": [
    "$$ argmin_i  ||x_i - z_j||_2 $$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "otherwise-waste",
   "metadata": {},
   "outputs": [],
   "source": [
    "def KNN(X, Y, Z, k):\n",
    "    res=[]\n",
    "    for j in range(m):\n",
    "        d=np.zeros(n)\n",
    "        for i in range(n):\n",
    "            # Find the distance from each point \n",
    "            d[i]=np.linalg.norm(X[i,:]-Z[j,:], 2)\n",
    "\n",
    "        c=np.argsort(d)\n",
    "        label=Counter(Y[c[0:k]]).most_common()[0][0]\n",
    "        res.append(label)\n",
    "    return res"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "expected-lewis",
   "metadata": {},
   "source": [
    "$$ argmin_j  ||x_i - z_j||_2 $$\n",
    "\n",
    "$$||x_i - z_j||_2 = \\sqrt{(x_i - z_j)^T (x_i-z_j)} = \\sqrt{x_i^T x_i -2 x_i^T z_j + z_j^T z_j} $$\n",
    "\n",
    "- $ diag(X~X^T)$, can be used to get $x_i^T x_i$\n",
    "\n",
    "- $X~Z^T $, can be used to get $x_i^T z_j$\n",
    "\n",
    "- $diag(Z~Z^T)$, can be used to get $z_j^T z_j$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "parental-method",
   "metadata": {},
   "outputs": [],
   "source": [
    "def KNN_vectorized(X, Y, Z, k):\n",
    "    \n",
    "    # Find the distance from each point \n",
    "    XX= np.tile(np.diag(np.matmul(X, X.T)), (m,1) ).T\n",
    "    XZ=np.matmul(X, Z.T)\n",
    "    ZZ= np.tile(np.diag(np.matmul(Z, Z.T)), (n,1)) \n",
    "    D= np.sqrt(XX-2*XZ+ZZ)\n",
    "    res=[]\n",
    "    for j in range(m):\n",
    "        c=np.argsort(D[:,j])\n",
    "        label=Counter(Y[c[0:k]]).most_common()[0][0]\n",
    "        res.append(label)\n",
    "    \n",
    "    return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "false-reader",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.022996902465820312 seconds\n"
     ]
    }
   ],
   "source": [
    "start=time.time()\n",
    "res = KNN(X, Y, Z, k)\n",
    "print(time.time()-start,'seconds')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "contemporary-chess",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.0029761791229248047 seconds\n"
     ]
    }
   ],
   "source": [
    "start=time.time()\n",
    "res = KNN_vectorized(X, Y, Z, k)\n",
    "print(time.time()-start,'seconds')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fancy-enlargement",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
